<?php
namespace app\common\process;

class UserInfo extends Info {
    public function update($user) {
        $post = input('post.');
        $validate = $this->validate;
        $model = $this->model;

        if(!$validate->scene('update')->check($post)) {
            $this->error($validate->getError());
        }
        $row = $model->where('id', $user['id'])->find();
        return $row->allowField(['photo', 'nickname', 'username'])->save($post);
    }

    //获取密码登录的用户名
    public function username() {
        $validate = $this->validate;
        $model = $this->model;
        $post = loader()->loadAny('request', 'tyyh\\User')->username();
        if(!$validate->scene('username')->check($post)) {
            $this->error($validate->getError());
        }
        $row = $this->model->find($post['id']);
        $this->assign('username', $row['username']);
        return $this->fetch();
    }

    //设置用户名和密码
    public function set_user_password() {
        $validate = $this->validate;
        $model = $this->model;
        $post = loader()->loadAny('request', 'tyyh\\User')->set_user_password();
        if(!$validate->scene('set_user_password')->check($post)) {
            $this->error($validate->getError());
        }

        $passwordTool = loadTool('Password');
        $result = $passwordTool->encryption($post['password'], '', true);
        return $model->save(['username' => $post['username'], 'password' => $result['password'], 'salt' => $result['salt']], ['id' =>$post['id']]);
    }

    //修改密码
    public function set_password($user) {
        $post = input('post.');
        $validate = $this->validate;

        if(!$validate->scene('set_password')->check($post)) {
            $this->error($validate->getError());
        }

        $passwordTool = loadTool('Password');
        $result = $passwordTool->encryption($post['newpassword'], '', true);

        $model = loadOnly('tyyh\\User')->find4username($post['username']);
        $model->password = $result['password'];
        $model->salt = $result['salt'];
        return $model->save();
    }
}